<template>
  <!-- 大盒子 -->
  <div class="MedicenCata">
    <!--  描述  -->
    <div class="header">
      <div class="header-icon">
        <i class="el-icon-byj"
           style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;background-color: #409EFF;color: #fff;"></i>
        <span style="font-size: 12px;font-weight:400;margin-left: 12px;">支付订单</span>
        <!--        <div class="feetbtn">
                  <el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="small"
                             plain @click="feetHandClick(v)">{{ v.label }}
                  </el-button>
                </div>-->
      </div>
    </div>
    <!-- 主体内容 -->
    <div class="main">
      <!-- left -->
      <div class="main-left">
        <!-- tree -->
        <el-tree
            ref="treeRef"
            :data="elTree"
            :props="defaultProps"
            node-key="label"
            :default-expanded-keys="['全部']"
            accordion
            @node-click="handleNodeClick"
            class="custom-tree"
        >
					<span class="custom-tree-node" slot-scope="{ node, data }" style="font-size: 12px;">
						<span :name="node.label">
							<i v-if="!data.children"
                 :class="node.expanded ? 'el-icon-openFile' : 'el-icon-closeFiles'"></i>
							<i v-else class="el-icon-openFile"></i>{{ node.label }}
						</span>
					</span>
        </el-tree>
      </div>
      <!-- right -->
      <div class="main-right" ref="mainRight">
        <!-- tit -->
        <div class="main-icon"
             style="display: flex; align-items: center; padding: 8px 10px; background: #fff; border-bottom: 1px solid #ebeef5;">
          <!-- 左侧图标和标题 -->
          <div class="main-icon-a" style="display: flex; align-items: center; margin-right: 15px;">
            <i :class="iconComes"
               style="border-radius: 50%; font-size: 20px; padding: 6px; background-color: #5a5a5a; color: #fff;"></i>
            <span style="font-size: 12px; font-weight: bold; margin-left: 8px; color: #606266;">{{
                CatalogueName
              }}</span>
          </div>

          <!-- 中间区域（所有筛选条件和按钮都在一行） -->
          <div style="display: flex; align-items: center; flex-wrap: nowrap;">
            <!-- 状态下拉 -->
<!--            <div class="main-icon-b" style="margin-right: 20px;">
              <span style="font-size: 12px; color: #606266; font-weight: bold;">支付状态:</span>
              <el-dropdown @command="handleCommand" trigger="click" style="margin-left: 4px;">
                <span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="0" divided>全部</el-dropdown-item>
                  <el-dropdown-item command="1">订单生成</el-dropdown-item>
                  <el-dropdown-item command="2">支付中</el-dropdown-item>
                  <el-dropdown-item command="3">支付成功</el-dropdown-item>
                  <el-dropdown-item command="4">支付失败</el-dropdown-item>
                  <el-dropdown-item command="5">已撤销</el-dropdown-item>
                  <el-dropdown-item command="6">已退款</el-dropdown-item>
                  <el-dropdown-item command="7">订单关闭</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>-->

            <!-- 搜索框 -->
            <div style="display: flex; align-items: center; margin-right: 8px;">
              <span style="font-size: 12px; color: #606266; font-weight: bold; margin-right: 6px;">关键字：</span>
              <el-select v-model="queryConditionForm.patientId"  placeholder="患者查询" size="mini"
                         @focus="getDocphrByCondtion" filterable clearable @change="loadData">
                <el-option
                    v-for="(item,index) in docphrOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                >
                </el-option>
              </el-select>
            </div>

            <div class="block">
              <el-date-picker
                  size="mini"
                  v-model="queryConditionForm.timeFrameArr"
                  type="datetimerange"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleConditionQuery"
                  :picker-options="pickerOptions">
              </el-date-picker>
            </div>

            <!-- 按钮组（直接跟在时间选择器后面） -->
            <div style="display: flex; align-items: center;">
              <el-button
                  v-for="(v,i) in headerBtn"
                  :key="i"
                  :type="v.type"
                  :loading="loading"
                  :icon="v.icon"
                  size="mini"
                  :style="{...v.style, 'margin-left': '6px'}"
                  @click="handClick(i)">
                {{ v.title }}
              </el-button>
            </div>
          </div>
        </div>
        <!-- table -->
        <div class="table">
          <el-table :data="tableData" border :style="{ width: windowWidth + 'px' }" @row-dblclick="handleDbShowData"
                    show-summary  :summary-method="getSummaries"
                    style="flex: 1; overflow-y: auto;">
            <el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop"
                             :label="col.name" header-align="center" :render-header="labelHead"
                             :min-width="getColumnWidth(col.label,col.prop,tableData)">
              <template #default="{ row }">
                  <span v-if="col.prop === 'payMoney'" class="money-cell">
                    ¥ {{ safeGetMappedValue(col, row) }}
                  </span>
                <span v-else>
                    {{ safeGetMappedValue(col, row) }}
                  </span>
              </template>

            </el-table-column>
            <!-- fixed -->
            <el-table-column fixed="left" label="行号" type="index"></el-table-column>
            <el-table-column fixed="right" label="操作" width="148">
              <template slot-scope="scope">
                <div class="editbox" style="text-align: center;">
                  <el-button
                      type="primary"
                      :disabled="scope.row.state !== '2'"
                      :loading="scope.row.loading || false"
                      @click="openRefundDialog(scope.row)"
                      size="mini"
                  >
                    {{ scope.row.loading ? '处理中...' : '退款' }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-dialog
            title="请输入退款金额"
            :visible.sync="refundDialogVisible"
            width="20%"
            @close="resetRefundForm"
        >

          <el-form size="mini" label-width="100px" :model="refundForm" :rules="refundRules" ref="refundForm">
            <el-row>
              <el-col :span="24">
                <el-form-item label="退款金额" prop="amount">
                  <el-input
                      v-model="refundForm.amount"
                      style="width: 60%"
                      placeholder="请输入退款金额"
                      type="number"
                      :min="0"
                      :max="currentOrder.refundMoney"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <span slot="footer" class="dialog-footer">
    <el-button @click="refundDialogVisible = false" size="mini">取消</el-button>
    <el-button type="primary" @click="confirmRefund" size="mini">确定</el-button>
  </span>
        </el-dialog>

        <el-dialog
            :title="addSqbUserKeysForm.id ? '修改商户密钥' : '新增商户密钥'"
            :visible.sync="sqbUserKeysFormDialogVisible"
            width="50%"
            @close="handleCloseAddorEditUserKey"
            class="custom-form-dialog"
        >
          <el-form
              :model="addSqbUserKeysForm"
              ref="addSqbUserKeysForm"
              :rules="addSqbUserKeysFormRules"
              label-width="120px"
              label-position="right"
              :disabled="showSqbUserKeysFormDialogVisible"
          >
            <!-- 第一行：应用编号 + 终端名称 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="应用编号:" prop="appId" class="no-wrap-label">
                  <el-input v-model="addSqbUserKeysForm.appId" placeholder="如：HT20230001" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="终端名称:" prop="name" class="no-wrap-label">
                  <el-input v-model="addSqbUserKeysForm.name" clearable/>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行：终端编号 + 设备序列号 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="终端编号:" prop="clientSn" class="no-wrap-label">
                  <el-input v-model="addSqbUserKeysForm.clientSn" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备序列号:" prop="deviceId" class="no-wrap-label">
                  <el-input v-model="addSqbUserKeysForm.deviceId" clearable/>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行：激活码 + 服务商密钥 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="激活码:" prop="code" class="no-wrap-label">
                  <el-input v-model="addSqbUserKeysForm.code" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务商密钥:" prop="vendorKey" class="no-wrap-label">
                  <el-input v-model="addSqbUserKeysForm.vendorKey" clearable/>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 单行：服务商序列号 -->
            <el-form-item label="服务商序列号:" prop="vendorSn" class="no-wrap-label">
              <el-input
                  v-model="addSqbUserKeysForm.vendorSn"
                  class="disabled-input"
              />
            </el-form-item>

            <!-- 设备信息（文本域） -->
            <el-form-item label="设备信息:" prop="osInfo" class="no-wrap-label">
              <el-input
                  type="textarea"
                  v-model="addSqbUserKeysForm.osInfo"
                  :rows="3"
                  resize="none"
                  show-word-limit
                  maxlength="200"
              />
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="handleCloseAddorEditUserKey">取消</el-button>
            <el-button type="primary" @click="handleAddorEditUserKey">保存</el-button>
          </div>
        </el-dialog>

      </div>
    </div>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[8, 16, 24]"
        :page-size="pageSize"
        :total="totalSize"
        layout="total, sizes, prev, pager, next, jumper"
        background
    >
    </el-pagination>
  </div>
</template>

<script>
import {getContuntList, getDeptList} from "@/api/reservation/reservation";
import {
  getBeforeHistoryTemplate,
  getComplaintemplate,
  getNowHistoryTemplate,
} from "@/api/reservation/caseHistoryTemplate";
import {getDoctorList} from "@/api/scheduling/scheduling";
import {getOnCredit} from "@/api/reservation/onCredit";
import {editOnCredit} from "@/api/reservation/outpatientCharge";
import {
  activateSqbUserKeys,
  addSqbUserKeys,
  editSqbUserKeys,
  signInSqbUserKeys
} from "@/api/thirdpartyPayment/thirdpartyPayment";
import dayjs from "dayjs";
import {getAllUser} from "@/api/user";
import {getDocphrByCondtion} from "@/api/reservation/outpatientPhysician";
import {doccliniclist} from "@/api/cinic/cinic";
import {getPayOrder, orderRefund} from "@/api/payOrder/payOrder";

export default {
  inject: ['reload'], // 无痕刷新
  components: {},
  data() {
    return {
      //时间框
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      // 树菜单Props
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // str
      windowWidth: '', //右侧表格动态宽度
      searchValue: '',
      beginTime: '',
      endTime: '',
      CatalogueName: '支付订单',
      DropDownedName: '全部',
      state: null,
      iconComes: 'el-icon-byj',

      //模态框控制
      loading: false,
      sqbUserKeysFormDialogVisible: false,
      showSqbUserKeysFormDialogVisible: false,
      refundDialogVisible: false,//退款
      currentOrder: {},
      refundForm: {
        amount: null,
      },
      refundRules: {
        amount: [
          { required: true, message: '请输入退款金额', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error('退款金额必须大于0'));
              } else if (value > this.currentOrder.payMoney) {
                callback(new Error('退款金额不能超过剩余支付金额'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },

      //分页参数
      pageNum: 1,
      pageSize: 8,
      totalSize: 10,

      //下拉框
      contractUnitOption: [],//合约单位
      stateOption: [{id: 0, label: '禁用'}, {id: 1, label: '可用'}],
      businessTypeOption: [{id: '1', label: '挂号'}, {id: '2', label: '门诊收费'}],
      orderStateTypeOption: [
        {id: '0', label: '订单生成'}, {id: '1', label: '支付中'},
        {id: '2', label: '支付成功'}, {id: '3', label: '支付失败'},
        {id: '4', label: '已撤销'}, {id: '5', label: '全额退款'},
        {id: '6', label: '退款失败'},{id: '7', label: '部分退款'},{id: '8', label: '订单关闭'}
      ],

      payTypeOption: [
        {id: '1', label: '现金'}, {id: '2', label: '支付宝'},
        {id: '3', label: '微信'}, {id: '4', label: '银行卡'}, {id: '5', label: '医保'},
        {id: '6', label: '收钱吧'},{id: '7', label: '部分退款'},{id: '8', label: '订单关闭'},{id: '9', label: '组合支付'}
      ],
      userOptions: [],//用户
      docphrOptions: [],//健康档案
      clinicOptions: [],//诊所列表
      loadding: false,

      //表单验证
      addSqbUserKeysFormRules: {
        appId: [
          {required: true, message: '应用编号不能为空', trigger: 'blur'},
          {pattern: /^[A-Za-z0-9]+$/, message: '只能包含字母和数字'}
        ],
        clientSn: [
          {required: true, message: '终端编号不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '长度在6到20个字符之间'}
        ],
        code: [
          {required: true, message: '激活码不能为空', trigger: 'blur'},
          {pattern: /^[A-Z0-9-]+$/, message: '格式如：ACTV-5XK9-7P2Q'}
        ],
        deviceId: [
          {required: true, message: '设备序列号不能为空', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '终端名称不能为空', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在2到50个字符之间'}
        ],
        vendorKey: [
          {required: true, message: '服务商密钥不能为空', trigger: 'blur'},
          {pattern: /^[A-Z0-9-]+$/, message: '格式如：VK-1Q2W-3E4R'}
        ],
        vendorSn: [
          {required: true, message: '服务商序列号不能为空', trigger: 'blur'}
        ]
      },

      //表单容器
      addSqbUserKeysForm: {
        id: null,
        appId: '',//应用编号
        clientSn: '',//客户方终端编号
        code: '',//激活码
        deviceId: '',//客户方收银终端序列号
        name: '',//客户方终端名称
        osInfo: '',//设备信息
        vendorKey: '',//服务商密钥
        vendorSn: '',//服务商序列号
      },
      queryConditionForm: {
        patientId: '',
        timeFrameArr: [],
      },

      //表格容器
      tableData: [],

      //动态按钮
      headerBtn: [
        {search: "search", title: "搜索", type: "success", style: {marginLeft: "-20px"}},
        {refesh: "refesh", title: "刷新", type: "", icon: "el-icon-refresh"},
      ],
      //侧边树
      elTree: [
        {
          label: '全部',
          path: '',
          title: '',
          icon: 'el-icon-news',
          children: [
            {label: '现金', path: '', title: '现金支付', icon: 'el-icon-money', paymentType: 1},
            {label: '支付宝', path: '', title: '支付宝支付', icon: 'el-icon-alipay', paymentType: 2},
            {label: '微信', path: '', title: '微信支付', icon: 'el-icon-wechat', paymentType: 3},
            {label: '银行卡', path: '', title: '银行卡支付', icon: 'el-icon-bank-card', paymentType: 4},
            {label: '医保', path: '', title: '医保支付', icon: 'el-icon-first-aid-kit', paymentType: 5},
            {label: '收钱吧', path: '', title: '收钱吧支付', icon: 'el-icon-collection', paymentType: 6}
          ]
        }
      ],

      //动态列容器
      tableRows: [
        {name: "诊所序号", prop: "clinicId"},
        {name: "诊所名称", prop: "clinicId", op: 'clinicOptions'},
        {name: "患者名称", prop: "userId", op: 'docphrOptions'},
        {name: "业务类型", prop: "businessType", op: 'businessTypeOption'},
        {name: "创建时间", prop: "createTime"},
        {name: "订单编号", prop: "orderNum"},
        {name: "订单状态", prop: "state", op: 'orderStateTypeOption'},
        {name: "支付金额", prop: "payMoney"},
        {name: "已退金额", prop: "refundMoney"},
        {name: "支付方式", prop: "payType", op: 'payTypeOption'},
        {name: "支付简介", prop: "remark"},
        {name: "第三方订单号", prop: "snNum"},
        {name: "订单支付成功时间", prop: "successTime"},
        {name: "退款时间", prop: "refundTime"},

      ],


      areaOption: [{id: 1, label: '省内'}, {id: 2, label: '省外'}, {id: 3, label: '进口'}],


    };
  },
  mounted() {
    this.loadData();
    this.getDocphrByCondtion();
    this.doccliniclist();
    this.$nextTick(() => {
      this.updateWindowWidth();
      window.addEventListener('resize', this.updateWindowWidth);
    })
  },
  methods: {
    openRefundDialog(row) {
      this.currentOrder = row;
      this.refundDialogVisible = true;
    },

    // 重置退款表单
    resetRefundForm() {
      this.refundForm.amount = null;
      this.$refs.refundForm?.resetFields();
    },

    confirmRefund() {
      this.$refs.refundForm.validate(valid => {
        if (valid) {
          this.handleOrderRefund({
            ...this.currentOrder,
            refundAmount: this.refundForm.amount
          });
          this.refundDialogVisible = false;
        }
      });
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];

      // 需要计算的字段配置
      const calcFields = {
        'payMoney': '支付金额',
      };

      columns.forEach((column, index) => {
        // 第一列显示行号（留空）
        if (index === 0) {
          sums[index] = '';
          return;
        }

        // 第二列（剂量单位）显示"合计"文字
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        // 只处理需要计算的字段
        if (calcFields[column.property]) {
          const total = data.reduce((sum, item) => {
            const value = parseFloat(item[column.property]) || 0;
            return sum + value;
          }, 0);

          // 如果是cnt列，显示为整数，否则保留两位小数
          sums[index] = column.property === 'cnt'
              ? Math.round(total).toString()
              : total.toFixed(2);
        } else {
          // 其他列显示占位符（与图片中的"一"一致）
          sums[index] = '';
        }
      });

      return sums;
    },

    async handleOrderRefund(orderWithAmount) {
      // 先检查订单状态
      if (orderWithAmount.state !== '2' && orderWithAmount.state !== '7') {
        this.$message.warning(`${orderWithAmount.orderNum} 该订单未支付成功，不能退款！`);
        return;
      }


      // 设置加载状态
      this.$set(this.tableData, 'loading', true);

      try {
        // 确认对话框
        const confirmResult = await this.$confirm(
            `是否确认退款订单 ${orderWithAmount.orderNum}?`, '退款确认', {confirmButtonText: '确认退款', cancelButtonText: '取消', type: 'warning'}
        ).catch(() => {
          // 用户点击了取消
          this.$message.warning(`已取消订单 ${orderWithAmount.orderNum} 的退款操作`);
          return false;
        });

        // 如果用户取消，直接返回
        if (!confirmResult) return;

        // 执行退款操作
        console.log(orderWithAmount,'orderWithAmountorderWithAmount')
        const res = await orderRefund({amount:orderWithAmount.refundAmount,orderNum: orderWithAmount.orderNum});

        if (res.data === "REFUND_SUCCESS") {
          this.$message.success("退款成功，1-5分钟之内到账");
          await this.loadData(); // 刷新数据
        } else {
          this.$message.error("系统异常：退款操作失败，请联系管理员");
        }
      } catch (error) {
        // 捕获其他异常
        console.error("退款操作异常:", error);
        this.$message.error("系统异常：请联系管理员");
      } finally {
        // 无论成功失败都取消加载状态
        this.$set(this.tableData, 'loading', false);
      }
    },

    async doccliniclist() {
      if (this.clinicOptions.length > 0) return;
      const res = await doccliniclist();
      this.clinicOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
    },

    async getDocphrByCondtion() {
      if (this.docphrOptions.length > 0) return;
      const res = await getDocphrByCondtion();
      this.docphrOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
    },
    async handleConditionQuery() {
      const res = await getPayOrder({
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        name: this.queryConditionForm.name,
        startTime: this.queryConditionForm.timeFrameArr[0],
        endTime: this.queryConditionForm.timeFrameArr[1]
      });
      if (res.code === 200) {
        this.tableData = res.data.content;
        this.totalSize = res.data.totalSize;
      }

    },

    //新增修改
    async handleAddorEditUserKey() {
      try {
        // 验证表单
        const valid = await this.$refs.addSqbUserKeysForm.validate();
        if (!valid) {
          this.$message.warning('请完善表单信息');
          return false;
        }

        let res;
        // 判断是新增还是编辑
        if (this.addSqbUserKeysForm.id) {
          // 有id -> 编辑操作
          res = await editSqbUserKeys(this.addSqbUserKeysForm);
        } else {
          // 无id -> 新增操作
          res = await addSqbUserKeys(this.addSqbUserKeysForm);
        }

        // 统一处理响应
        if (res.code === 200) {
          this.handleCloseAddorEditUserKey();
          await this.loadData();
        } else {
          this.$message.error(res.message || '操作失败');
        }
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败，请重试');
      }
    },

    //合约单位下拉框
    async getContuntList() {
      if (this.contractUnitOption.length > 0) return;
      const res = await getContuntList();
      this.contractUnitOption = res.data.map(item => {
        return {id: item.id, label: item.name}
      })
    },

    //关闭模态框清空数据
    handleCloseAddorEditUserKey() {
      this.addSqbUserKeysForm = {};
      this.$nextTick(() => {
        this.$refs.addSqbUserKeysForm.clearValidate();
      });
      this.sqbUserKeysFormDialogVisible = false;
    },

    //科室下拉框
    async getDeptList() {
      const res = await getDeptList()
      this.deptOptions = res.data.map(item => {
        return {id: item.id, label: item.deptName}
      })
    },

    //医生下拉框
    async getDoctorList() {
      const res = await getDoctorList()
      this.doctorOptions = res.data.map(item => {
        return {id: item.id, label: item.fullName}
      }) 
    },

    //医生下拉框
    async getAllUser() {
      const res = await getAllUser({
        pageSize: 100,
        pageNum: 1,
      })
      this.userOptions = res.data.content.map(item => {
        return {id: item.userId, label: item.username}
      })
    },

    //启用禁用
    async handleStartOrDisabled(row) {
      try {
        // 确认弹框
        const confirmMessage = row.state === 1 ? `确定要禁用${row.name}吗？` : `确定要启用${row.name}吗？`;
        const confirmResult = await this.$confirm(confirmMessage, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          return false;
        });

        // 如果用户点击取消，直接返回
        if (!confirmResult) return;

        // 执行状态修改
        this.addOnCreditForm = row;
        this.addOnCreditForm.state = row.state === 1 ? 0 : 1;
        const res = await editOnCredit(this.addOnCreditForm);
        if (res.code === 200) {
          await this.loadData();
        } else {
          this.$message.error(`修改${this.addOnCreditForm.name}状态失败`);
        }
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作过程中发生错误');
      }
    },

    //双击查看的当前行信息
    handleDbShowData(row) {
      this.addOnCreditForm = row;
      this.sqbUserKeysFormDialogVisible = true;
      this.showSqbUserKeysFormDialogVisible = true;
    },

    //表格字段映射
    safeGetMappedValue(col, row) {
      // 1. 检查数据有效性
      const rawValue = row[col.prop];
      if (rawValue === null || rawValue === undefined) return ' ';

      // 2. 检查映射数组
      const mapArray = this[col.op];
      if (!col.op || !Array.isArray(mapArray)) return rawValue;

      // 3. 执行映射
      const matched = mapArray.find(item => item.id === rawValue);
      return matched?.label || rawValue;
    },

    //数据源
    async loadData() {
      const res = await getPayOrder({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        patientId: this.queryConditionForm.patientId === '' ? '' : this.queryConditionForm.patientId,
        startTime: this.queryConditionForm.timeFrameArr[0],
        endTime: this.queryConditionForm.timeFrameArr[1],
      });
      if (res.code === 200) {
        this.totalSize = res.data.totalSize;
        this.tableData = res.data.content.map(item => {
          return {
            ...item,
            createTime: item.createTime === null ? null : dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss'),
            successTime: item.successTime === null ? null : dayjs(item.successTime).format('YYYY-MM-DD HH:mm:ss'),
            refundTime: item.refundTime === null ? null : dayjs(item.refundTime).format('YYYY-MM-DD HH:mm:ss'),
            payMoney: item.payMoney !== null ? Number(item.payMoney).toFixed(2) : null
          }
        })
      } else {
        this.$message.error(`系统异常`)
      }
    },

    //侧边树(全部)按钮
    handleNodeClick(data, e) {
      this.searchValue = '';
      this.loadData()
    },

    //动态计算列宽
    columnWidth(col, list) {
      let prop = col.prop, lab = col.lab;
      let width = 40; // 设定一个最小值
      let maxlenStr = ""; // 最长字符串
      for (let info of list) {
        if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
      }
      width = Math.max(width, len(lab), len(maxlenStr));
      // 表格自带的内边距(20px) 自调
      return width + 12; // 这里加了 12px
      function len(str) {
        // 实际分配长度可根据需要自行调整
        let length = 8;
        for (const char of str + "") {
          // 英文小写字符 8px
          if ("a" <= char && char <= "z") length += 8;
          // 英文大写字符 8px
          else if ("A" <= char && char <= "Z") length += 8;
          // 中文字符 28px
          else if (char >= "\u4e00" && char <= "\u9fa5") length += 32;
          // 其他 8px
          else length += 12;
        }
        return length;
      }
    },

    // 步骤
    async handClick(i) {
      console.log(i, 'handClickhandClickhandClickhandClick222222222222222')
      switch (i) {
        case 0:
          await this.loadData();
          break;
        case 1:
          // 处理索引0的逻辑 => 刷新
          this.loading = true;
          setTimeout(() => {
            this.reload();
            this.$message({type: 'success', message: '已刷新'})
            this.loading = false;
          }, 1500)
          break;
        case 2:
          // 处理索引1的逻辑
          this.$confirm('敬请期待')
              .then(_ => {
              })
              .catch(_ => {
              });
          break;
      }
    },

    //状态查询
    async handleCommand(command) {
      const numericValue = command === 'a' ? 1 : command === 'b' ? 0 : command === 'c' ? null : null;
      this.state = numericValue == null ? null : numericValue;
      this.DropDownedName = command === 'a' ? '可用' : command === 'b' ? '禁用' : '全部';
      switch (this.currentNode) {
        case 1:
          let res1 = await getComplaintemplate({
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            state: numericValue == null ? null : numericValue,
            condition: this.searchValue === '' ? '' : this.searchValue
          });
          if (res1.code === 200) {
            this.$message({
              type: 'success',
              message: '查询成功！',
            });
            this.tableData = res1.data.content;
            this.totalSize = res1.data.totalSize;
          } else {
            this.$message({
              type: 'error',
              message: res1.message,
            });
          }
          break;

        case 2:
          let res2 = await getBeforeHistoryTemplate({
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            state: numericValue == null ? null : numericValue,
            condition: this.searchValue === '' ? '' : this.searchValue
          });
          if (res2.code === 200) {
            this.$message({
              type: 'success',
              message: '查询成功！',
            });
            this.tableData = res2.data.content;
            this.totalSize = res2.data.totalSize;
          } else {
            this.$message({
              type: 'error',
              message: res2.message,
            });
          }
          break;


        case 3:
          let res3 = await getNowHistoryTemplate({
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            state: numericValue == null ? null : numericValue,
            condition: this.searchValue === '' ? '' : this.searchValue
          });
          if (res3.code === 200) {
            this.$message({
              type: 'success',
              message: '查询成功！',
            });
            this.tableData = res3.data.content;
            this.totalSize = res3.data.totalSize;
          } else {
            this.$message({
              type: 'error',
              message: res3.message,
            });
          }
          break;
      }
    },

    // 实时宽度
    updateWindowWidth() {
      this.windowWidth = window.innerWidth - 328;
    },

    //分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.loadData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadData();
    },
    getColumnWidth(label, prop, tableData) {
      const minWidth = 80;
      const padding = 30; // 增加边距缓冲
      const contentList = tableData.map(item => item?.[prop] ?? '');

      // 计算所有内容宽度（包括表头）
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },

    // 精确计算文本宽度（使用Canvas）
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },

    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-dialog__header {
  padding: 18px;
  background-color: #007bb0;
}

/deep/ .el-dialog__title {
  font-size: 18px;
  color: #fff;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.dialog {
  .showDialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }
}


// content
.MedicenCata {
  height: 100%;
  width: 100%;
  // header
  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    background-color: #efefef;
    padding: 4px;

    // justify-content: space-evenly;
    // icon
    .header-icon {
      display: flex;
      align-items: center;
    }

    .feetbtn {
      display: flex;
      justify-content: center;
      margin-left: 12px;
    }
  }

  // main
  .main {
    width: 100%;
    display: flex;
    justify-content: space-between;
    // height: 473px; /* 设置父容器的高度 */
    // overflow-y: auto; /* 当内容超出容器高度时显示垂直滚动条 */
    // left
    .main-left {
      .custom-tree {
        max-height: 100%; /* 设置树形菜单的最大高度为父容器的100% */
        overflow-y: auto; /* 当内容超出设定高度时显示滚动条 */
      }

      /deep/ .el-tree-node__content {
        // height: 40px;
        // padding-right: 8px !important;
      }

      /deep/ .el-tree-node__label {
        font-size: 12px;
      }

      width: 128px;
      height: 100%;
    }

    // right
    .main-right {
      flex: 4;
      height: 100%;
      // alert
      .addmessagesBox {
        .tabs {
          /deep/ .el-select > .el-input {
            width: 172px;
          }

          /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
            width: 172px;
          }

          /deep/ .el-form-item__content {
            display: flex;

            span {
              font-size: 12px;
            }
          }

          .oneLine {
            width: 524px;
            // background-color: indianred;
          }
        }

        /deep/ .el-dialog__title {
          font-size: 12px;
        }

        /deep/ .el-table {
          font-size: 12px;
        }

      }

      // icon
      .main-icon {
        display: flex;
        align-items: center;
        padding: 12px;
        line-height: 40px;

        .main-icon-a {
          // width: 240px;
          // background-color: #00557f;
        }

        .main-icon-b {
          margin-left: 28px;

          /deep/ .el-dropdown {
            font-size: 12px;
            cursor: pointer;
          }

          /deep/ .el-dropdown:hover {
            font-weight: bold;
            color: #66b1ff;
          }

          /deep/ .el-icon--right {
            // background-color: #66b1ff;
          }

          /deep/ .el-popper[x-placement^=bottom] {
            margin-top: 0;
          }
        }

        // c
        .main-icon-c {
          display: flex;
          margin-left: 28px;

          /deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b] {
            width: 70%;
          }
        }
      }

      // table
      /deep/ .el-table .cell {
        font-size: 12px;
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div :first-child {
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div {
        text-align: center;
        overflow: hidden;
        white-space: normal;
        word-break: break-all;
      }

      .table {

      }
    }
  }

  // addModel
  .addModel {
    margin-left: 12px;

    /deep/ .el-dialog__header {
      padding: 12px;
      line-height: 28px;
      background-color: #007bb0;
    }

    /deep/ .el-dialog__title {
      color: #fff;
      font-size: 12px;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close:hover {
      background-color: brown;
    }

    /deep/ .el-form-item__label {
      font-size: 12px;
    }
  }

  .editModel {
    /deep/ .el-dialog__header {
      padding: 12px;
      line-height: 28px;
      background-color: #007bb0;
    }

    /deep/ .el-dialog__title {
      color: #fff;
      font-size: 12px;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close:hover {
      background-color: brown;
    }

    /deep/ .el-form-item__label {
      font-size: 12px;
    }
  }

  // feet
  .feet {
    padding: 12px;

  }

}
</style>